package com.shababeach.travel.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class WxDecryptUtil {
    private static final Logger logger = LoggerFactory.getLogger(WxDecryptUtil.class);

    public static String decrypt(String encryptedData, String sessionKey, String iv) {
        try {
            // 如果加密数据为空，直接返回空JSON
            if (encryptedData == null || encryptedData.isEmpty()) {
                return "{}";
            }

            // 1. 处理Base64数据，移除可能的特殊字符
            String encryptedDataBase64 = encryptedData.replaceAll("[^A-Za-z0-9+/=]", "");
            String sessionKeyBase64 = sessionKey.replaceAll("[^A-Za-z0-9+/=]", "");
            String ivBase64 = iv.replaceAll("[^A-Za-z0-9+/=]", "");

            // 2. 解码Base64数据
            byte[] encryptedDataBytes = Base64.decodeBase64(encryptedDataBase64);
            byte[] sessionKeyBytes = Base64.decodeBase64(sessionKeyBase64);
            byte[] ivBytes = Base64.decodeBase64(ivBase64);

            // 3. 执行AES解密
            byte[] resultByte = AES.decrypt(encryptedDataBytes, sessionKeyBytes, ivBytes);
            
            if (resultByte != null && resultByte.length > 0) {
                String userInfo = new String(resultByte, StandardCharsets.UTF_8);
                logger.info("解密成功，用户信息: {}", userInfo);
                return userInfo;
            } else {
                logger.warn("解密失败，返回空数据");
                return "{}";
            }
        } catch (Exception e) {
            logger.error("解密过程发生错误: {}", e.getMessage());
            return "{}";
        }
    }
} 